//
//  ShopCarView.m
//  shanHaiHuiApp
//
//  Created by DS on 2018/3/9.
//  Copyright © 2018年 徐双. All rights reserved.
//

#import "ShopCarView.h"
#import "ShopCarTableViewCell.h"
#import "ShopCarModel.h"

@interface ShopCarView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

Strong UITableView * tableView;
Copy void(^selectedHandle)(NSString *str);
Strong UIView * headView;
Strong UIView * footView;

//输入框的数量(加)
Strong NSString * countString;
Strong  NSString * pariceLabel;

//输入框的数量(减)
Strong NSString * countString1;
Strong  NSString * pariceLabel1;

@end

@implementation ShopCarView

#pragma mark -- Action
- (void)calculateBtnClick{
    
    if (_getCaulteClick) {
        _getCaulteClick();
    
    }  
}

//去掉小数点后面的0
-(NSString*)removeFloatAllZero:(NSString*)string
{
    NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}


//清空购物车按钮

- (void)clearButtonClick{
    
    [self.dataArr removeAllObjects];
    [self.tableView reloadData];
   // [self dismiss];
    
    if (_getClearClick) {
        _getClearClick();
    }
 
    BOOL isClearSuccess = [ClearCacheTool clearCacheWithFilePath:filePaths];

    if (isClearSuccess) {
        NSLog(@"清除成功");
        self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",0.00];
        self.countLabel.text = [NSString stringWithFormat:@"%d",0];

    }else{
        NSLog(@"清除失败");
    }
    
    
   
}

- (instancetype)initWithFrame:(CGRect)frame selectedHandle:(void (^)(NSString *))selectedHandle{
    if (self = [super initWithFrame:frame]) {
        self.alpha = 0;
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _selectedHandle = selectedHandle;
        backButton.backgroundColor = [UIColor blackColor];
        backButton.alpha = .6;
        backButton.titleLabel.font = DEF_FontSize_13;
        [backButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:backButton];
        [self addSubview:self.tableView];
        [self addSubview:self.bottomView];
        
    }
    return self;
}


#pragma mark --UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}



#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        
        if (kDevice_Is_iPhoneX) {
             _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, UNIT_HEIGHT(210), SCREEN_WIDTH, SCREEN_HEIGHT - UNIT_HEIGHT(210) - UNIT_HEIGHT(49) - height20) style:UITableViewStyleGrouped];
        }else{
            
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, UNIT_HEIGHT(210), SCREEN_WIDTH, SCREEN_HEIGHT - UNIT_HEIGHT(210) - UNIT_HEIGHT(49)) style:UITableViewStyleGrouped];
        }
        
       
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableView.tableHeaderView = self.headView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
        
    }
    return _tableView;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, UNIT_HEIGHT(210), SCREEN_WIDTH, UNIT_HEIGHT(120))];
        _headView.backgroundColor = getColor(whiteColor);
        
        _picImageView = [UIImageView new];
        _picImageView.image = [UIImage imageNamed:@"kahao"];
        _picImageView.contentMode = UIViewContentModeScaleAspectFit;
        
        _cardLabel = [[UILabel alloc] init];
        _cardLabel.text = @"卡号";
        _cardLabel.font = DEF_FontSize_11;
        _cardLabel.textColor = getColor(@"323232");
        
        _textField = [[UITextField alloc] init];
        _textField.keyboardType = UIKeyboardTypePhonePad;
        _textField.placeholder = @"请输入卡号";
        _textField.font = DEF_FontSize_11;
        _textField.textColor = getColor(@"323232");
        _textField.delegate = self;
        
        _textField.text = @"102203";
        
        
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = getColor(@"F0F0F0");
        
        _seletedLabel = [[UILabel alloc] init];
        _seletedLabel.font = DEF_FontSize_14;
        _seletedLabel.textColor = getColor(@"323232");
        _seletedLabel.text = @"已选商品";
        
        _clearShopCarBtn = [[UIButton alloc] init];
        [ _clearShopCarBtn setTitle:@"清空购物车" forState:UIControlStateNormal];
         _clearShopCarBtn.titleLabel.font = DEF_FontSize_11;
        [ _clearShopCarBtn setTitleColor:getColor(@"666666") forState:UIControlStateNormal];
        [ _clearShopCarBtn addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside];
        
        _lineView1 = [[UIView alloc] init];
        _lineView1.backgroundColor = getColor(dividerColor);
        
        [_headView sd_addSubviews:@[self.picImageView,self.cardLabel,self.textField,self.lineView,self.seletedLabel,self.clearShopCarBtn,self.lineView1]];
        
        [self layOutFrame];
        
    }
    return _headView;
}

- (void)layOutFrame{
    ws(self)
    [self.picImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(UNIT_HEIGHT(19));
        make.left.mas_equalTo(UNIT_WIDTH(15));
        make.height.mas_equalTo(17);
        make.width.mas_equalTo(21);
    }];
    
    [self.cardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakself.picImageView.mas_right).offset(6);
        make.centerY.mas_equalTo(weakself.picImageView.mas_centerY);
        make.width.mas_equalTo(UNIT_WIDTH(35));
        make.height.mas_equalTo(UNIT_HEIGHT(11));
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakself.cardLabel.mas_right).offset(5);
        make.right.mas_equalTo(UNIT_WIDTH(-10));
        make.height.mas_equalTo(UNIT_HEIGHT(30));
        make.centerY.mas_equalTo(weakself.picImageView.mas_centerY);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.textField.mas_bottom).offset(10);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.seletedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(UNIT_WIDTH(16));
        make.top.mas_equalTo(weakself.lineView.mas_bottom).offset(10);
        make.height.mas_equalTo(UNIT_HEIGHT(30));
    }];
    
    [self.clearShopCarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(UNIT_WIDTH(-10));
        make.centerY.mas_equalTo(weakself.seletedLabel.mas_centerY);
        make.height.mas_equalTo(UNIT_WIDTH(30));
        make.width.mas_equalTo(UNIT_HEIGHT(100));
    }];
    
    [self.lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.seletedLabel.mas_bottom).offset(10);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
}

// 底部视图

- (UIView *)bottomView{
    if (!_bottomView) {
        if (kDevice_Is_iPhoneX) {
            _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT  - height20 - UNIT_HEIGHT(49), SCREEN_WIDTH, UNIT_HEIGHT(49))];
        }else{
          _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame), SCREEN_WIDTH, UNIT_HEIGHT(49))];
        }
        
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        _shopImageview = [UIImageView new];
        _shopImageview.contentMode = UIViewContentModeScaleAspectFit;
        _shopImageview.image = [UIImage imageNamed:@"gouwuche"];
        
        _totalPriceLabel = [[UILabel alloc] init];
        _totalPriceLabel.textColor = getColor(@"EC4350");
        _totalPriceLabel.font = DEF_FontSize_18;
        _totalPriceLabel.text = @"￥999.6";
        
        _numberLabel = [[UILabel alloc] init];
        _numberLabel.font = DEF_FontSize_14;
        _numberLabel.textColor = getColor(@"323232");
        _numberLabel.text = @"销量 :";
        
        _countLabel = [[UILabel alloc] init];
        _countLabel.font =DEF_FontSize_14;
        _countLabel.textColor = getColor(@"323232");
        _countLabel.text = @"9999";
        
        _calculateBtn = [[UIButton alloc] init];
        _calculateBtn.backgroundColor = getColor(@"EC4350");
        [_calculateBtn setTitle:@"购物结算" forState:UIControlStateNormal];
        [_calculateBtn setTitleColor:getColor(@"FFFFFF") forState:UIControlStateNormal];
        [_calculateBtn addTarget:self action:@selector(calculateBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_bottomView sd_addSubviews:@[_shopImageview,_totalPriceLabel,_numberLabel,_countLabel,_calculateBtn]];
        
        _shopImageview.sd_layout
        .topSpaceToView(_bottomView ,UNIT_HEIGHT(12))
        .leftSpaceToView(_bottomView , UNIT_HEIGHT(16))
        .widthIs(UNIT_WIDTH(30))
        .heightIs(UNIT_HEIGHT(30));
        
        _totalPriceLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_shopImageview , UNIT_HEIGHT(6))
        .widthIs(UNIT_WIDTH(100))
        .heightIs(UNIT_HEIGHT(30));
        
        _numberLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_totalPriceLabel, UNIT_HEIGHT(6))
        .widthIs(UNIT_WIDTH(50))
        .heightIs(UNIT_HEIGHT(30));
        
        _countLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_numberLabel, UNIT_HEIGHT(0))
        .widthIs(UNIT_WIDTH(60))
        .heightIs(UNIT_HEIGHT(30));
        
        [_calculateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.width.mas_equalTo(UNIT_WIDTH(100));
        }];
    }
    return _bottomView;
}


#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopCarTableViewCell * cell = [ShopCarTableViewCell cellForTableView:tableView];
    
    cell.carModel = self.dataArr[indexPath.section];
    

    
    cell.carModel.goodCount = [cell.textField.text integerValue];

    
    if (cell.carModel.goodCount > 0) {
        cell.textField.hidden = NO;
        cell.perLabel.hidden = NO;
        cell.minusBtn.hidden = NO;
        
        self.countString = [NSString stringWithFormat:@"%ld",cell.carModel.goodCount];
        cell.textField.text = self.countString;
        
        CGFloat fdj2 = (CGFloat)[cell.carModel.perMoney floatValue];
        
        //去掉小数点末尾的0
        
        NSString * str = [NSString stringWithFormat:@"%f",cell.carModel.goodCount * fdj2];
        
        NSString *str1 = [self removeFloatAllZero:str];
        
        self.pariceLabel = [NSString stringWithFormat:@"￥%@",str1];
        
        cell.pariceLabel.text = self.pariceLabel;
        
        [self updateCountLabel];
        
        
    }
    
    
    
    cell.getJiaClick = ^(ShopCarTableViewCell *cell,UITextField * textField,UIImageView *imageView,UIButton * plusBtn) {
        
        //[self.view addSubview:self.bottomView];
        
        //加入购物车动画
        
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        
        CGRect rect1 = [_shopImageview convertRect: _shopImageview.bounds toView:window];
        
        CGRect rect2 = [plusBtn convertRect: plusBtn.bounds toView:window];
        
        
//        CGRect rect = [tableView rectForRowAtIndexPath:indexPath];
//        /// 获取当前cell 相对于self.view 当前的坐标
//        rect.origin.y          = rect.origin.y - [tableView contentOffset].y;
//        CGRect imageViewRect   = plusBtn.frame;
//        imageViewRect.origin.y = rect.origin.y + imageViewRect.origin.y;
        //
        [[PurchaseCarAnimationTool shareTool] startAnimationandView:imageView
                                                               rect:rect2
                                                        finisnPoint:CGPointMake(rect1.origin.x, rect1.origin.y)
                                                        finishBlock:^(BOOL finish) {
                                                            
                                                            [PurchaseCarAnimationTool shakeAnimation:_shopImageview];
                                                        }];
 
        
        
        [UIView animateWithDuration:1 animations:^{
            cell.textField.hidden = NO;
            cell.perLabel.hidden = NO;
            cell.minusBtn.hidden = NO;
       
            cell.carModel.goodCount = [textField.text integerValue];
            cell.carModel.goodCount += 1;
            
             self.countString = [NSString stringWithFormat:@"%ld",cell.carModel.goodCount];
            cell.textField.text =  self.countString;
            
            CGFloat fdj2 = (CGFloat)[cell.carModel.perMoney floatValue];
            
            NSString * str = [NSString stringWithFormat:@"%f",cell.carModel.goodCount * fdj2];
            
            NSString * str1 = [self removeFloatAllZero:str];
            
            cell.pariceLabel.text = [NSString stringWithFormat:@"￥%@",str1];
            
            [self updateCountLabel];
            
            
            if (_getPlusClick) {
                
                _getPlusClick(self,cell.carModel.goodCount,cell.carModel.serialNum);
            }
            
            
        }];
    };
        
  
    cell.getjianClick = ^(ShopCarTableViewCell *cell,UITextField * textField) {
        
        [UIView animateWithDuration:1 animations:^{
            
            cell.carModel.goodCount = [textField.text integerValue];
            
    
            cell.carModel.goodCount -= 1;
            self.countString1 = [NSString stringWithFormat:@"%ld",cell.carModel.goodCount];
            cell.textField.text = self.countString1;
            CGFloat fdj2 = (CGFloat)[cell.carModel.perMoney floatValue];
            
            NSString * str = [NSString stringWithFormat:@"%f",cell.carModel.goodCount * fdj2];
            NSString * str1 = [self removeFloatAllZero:str];
            
            cell.pariceLabel.text = [NSString stringWithFormat:@"￥%@",str1];
            if([cell.textField.text isEqualToString:@"0"]){

                [self.dataArr removeObjectAtIndex:indexPath.section];
                
                if ( self.dataArr.count == 0) {
                    
                     [self dismiss];
                    
                }
  
                
                [self.tableView reloadData];
            }
           
            [self updateCountLabel];
            
            
            if (_getMinusClick) {
                
                _getMinusClick(self,cell.carModel.goodCount,cell.carModel.serialNum);
            }
            
        }];
    };
    
    cell.getTextFieldClick = ^(ShopCarTableViewCell *cell,UITextField * textField) {
        
        
        [UIView animateWithDuration:1 animations:^{
            
 
            
            cell.carModel.goodCount = [textField.text integerValue];
            
            CGFloat fdj2 = (CGFloat)[cell.carModel.perMoney floatValue];
            
            NSString * str1 = [NSString stringWithFormat:@"%f",cell.carModel.goodCount * fdj2];
            
            NSString * strSub = [self removeFloatAllZero:str1];
            self.pariceLabel1 = [NSString stringWithFormat:@"￥%@",strSub];
            cell.pariceLabel.text = self.pariceLabel1;
            if([cell.textField.text isEqualToString:@"0"]){
                cell.textField.hidden = YES;
                cell.perLabel.hidden = YES;
                cell.minusBtn.hidden = YES;
                cell.pariceLabel.text = [NSString stringWithFormat:@"￥%ld",(long)cell.carModel.goodCount];
            }
            
            [self updateCountLabel];
            
            if (_getTextFieldClick) {
                
                _getTextFieldClick(self,cell.carModel.goodCount,cell.carModel.serialNum);
            }
            
            
        }];
    };
    
    
    
    return cell;
}

- (void)updateCountLabel {
    
   
    NSInteger count = 0;
    CGFloat totalPrice = 0;
    
    for (ShopCarModel *model in self.dataArr) {
        count += model.goodCount;
        CGFloat fdj2 = (CGFloat)[model.perMoney floatValue];
        totalPrice += model.goodCount * fdj2;
  
    }
    NSString * totalStr = [NSString stringWithFormat:@"%f",totalPrice];
    NSString * totalStr1 = [self removeFloatAllZero:totalStr];
    _totalPriceLabel.text = [NSString stringWithFormat:@"￥%@",totalStr1];
    _countLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UNIT_HEIGHT(120);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}



//添加编辑模式

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//左滑动出现的文字

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//删除所做的动作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    
    ShopCarModel * shopcarModel = self.dataArr[indexPath.section];

    [self.dataArr removeObjectAtIndex:indexPath.section];
 
    [self.tableView reloadData];
    
    
    if (_getDeletedClick) {
        
        
        if (_getDeletedClick) {
            
            _getDeletedClick(self,0,shopcarModel.serialNum);
        }
        
    }
    
    
    if ( self.dataArr.count == 0) {
        
        [self dismiss];
        
    }
    
     [self updateCountLabel];
    
   
}





#pragma mark -- 显示还是不显示
//出现
-(void)show{
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
    }];
}

//消失
-(void)dismiss{
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 0 ;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)setDict:(NSDictionary *)dict{
    
    _dict = dict;
    self.totalPriceLabel.text = [self.dict objectForKey:@"totalMoney"];
    self.countLabel.text = [self.dict objectForKey:@"totalCount"];
}



@end
